package ltd.jdsoft.cute.scheduler.configuration;

import java.util.List;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.util.CollectionUtils;

import ltd.jdsoft.cute.common.extention.ExtensionLoader;
import ltd.jdsoft.cute.common.util.PropertyUtil;
import ltd.jdsoft.cute.scheduler.spi.Scheduler;

/**
 * 定时调度器的初始化&配置器
 * 
 * @author zhengzhq
 *
 */
@Configuration
@EnableScheduling
public class SchedulerInitializer implements SchedulingConfigurer {

  private static Logger logger = LoggerFactory.getLogger(SchedulerInitializer.class);

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    logger.info("start init scheduler...");
    int taskPoolSize =
        PropertyUtil.getDefaultConfig("cute.scheduler.task.poolsize", Integer.class, 2);
    taskRegistrar.setScheduler(Executors.newScheduledThreadPool(taskPoolSize));
    List<Scheduler> schedulerExtList = ExtensionLoader.getExtensionList(Scheduler.class);

    if (!CollectionUtils.isEmpty(schedulerExtList)) {
      for (Scheduler scheduler : schedulerExtList) {
        initScheduler(taskRegistrar, scheduler);
      }
    } else {
      logger.info("no scheduler extension found.");
    }

    logger.info("end init scheduler...");
  }

  private void initScheduler(ScheduledTaskRegistrar taskRegistrar, Scheduler scheduler) {
    taskRegistrar.addCronTask(new Runnable() {

      @Override
      public void run() {
        scheduler.process();
      }
    }, scheduler.getExpression());
  }
}
